package me.xue.communityhealth.admin.controller;

import me.xue.communityhealth.model.DrugDepot;
import me.xue.communityhealth.service.DrugDepotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class DrugDepotController {

    private final DrugDepotService service;

    @Autowired
    public DrugDepotController(DrugDepotService service) {
        this.service = service;
    }

    @GetMapping("/drugDepots")
    public String all(Model model) {
        List<DrugDepot> drugDepots = service.findAll();
        model.addAttribute("drugDepots", drugDepots);
        return "drug_depots";
    }

    @GetMapping("/drugDepot/add")
    public String addPage(Model model) {
        model.addAttribute("drugDepot", new DrugDepot());
        return "drug_depot_edit";
    }

    @PostMapping("/drugDepot")
    public String add(DrugDepot drugDepot) {
        if (service.save(drugDepot) == 1) {
            return "redirect:/drugDepots";
        }
        return "drug_depot_edit";
    }

    @DeleteMapping("/drugDepot/{id:\\d+}")
    @ResponseBody
    public String delete(@PathVariable("id") Integer id) {
        if (service.delete(id) == 1) {
            return "success";
        }
        return "fail";
    }

    @GetMapping("/drugDepot/{id:\\d+}/edit")
    public String updatePage(@PathVariable("id") Integer id, Model model) {
        DrugDepot drugDepot = service.findOne(id);
        model.addAttribute("drugDepot", drugDepot);
        return "drug_depot_edit";
    }

    @PutMapping("/drugDepot")
    public String update(DrugDepot drugDepot) {
        if (service.update(drugDepot) == 1) {
            return "redirect:/drugDepots";
        }
        return "drug_depot_edit";
    }

}
